// 云函数入口文件
// const cloud = require('wx-server-sdk')

// cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// 云函数入口函数
const cloud = require('wx-server-sdk');
const xlsx = require('xlsx');

cloud.init();

exports.main = async (event, context) => {
  const { records } = event;
  const db = cloud.database();

  try {
    // 如果未传入记录，则从数据库中获取所有非 pending 的记录
    let data = records || [];
    if (!records) {
      const res = await db.collection('records')
        .where({ status: db.command.neq('pending') })
        .orderBy('applicationDate', 'desc')
        .get();
      data = res.data;
    }

    // 将数据转换为二维数组格式
    const worksheetData = [
      ['申请人', '申请时间', '状态', '批准人', '批准时间'], // 表头
    ];

    data.forEach((record) => {
      worksheetData.push([
        record.applicant || '',
        record.applicationDate ? new Date(record.applicationDate).toLocaleString() : '',
        record.status === 'approved' ? '已批准' : '已拒绝',
        record.approver || '',
        record.approvalDate ? new Date(record.approvalDate).toLocaleString() : '',
      ]);
    });

    // 创建工作簿
    const worksheet = xlsx.utils.aoa_to_sheet(worksheetData);
    const workbook = xlsx.utils.book_new();
    xlsx.utils.book_append_sheet(workbook, worksheet, '领用记录');

    // 将工作簿写入缓冲区
    const buffer = xlsx.write(workbook, { type: 'buffer', bookType: 'xlsx' });

    // 上传到云存储
    const uploadRes = await cloud.uploadFile({
      cloudPath: `export/records-${Date.now()}.xlsx`,
      fileContent: buffer,
    });

    return { success: true, fileID: uploadRes.fileID };
  } catch (err) {
    console.error(err);
    return { success: false, message: '导出失败，请稍后重试' };
  }
};